﻿using DataAccessLayer;
using DataRepositoryLayer.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataRepositoryLayer.Classes
{
    /// <summary>
    /// Entity Framework based implementation of UoW
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        /// <summary>
        /// Entity Framework context
        /// </summary>
        private DbContext context;
        private DbContextTransaction transaction;

        public DbContext Context
        {
            get { return context; }
        }

        public UnitOfWork()
        {
            context = new ElectricCarEntities();
            context.Configuration.ProxyCreationEnabled = false; //this would break WCF services
            context.Configuration.LazyLoadingEnabled = false;
        }

        public void Commit()
        {
            context.SaveChanges();
        }


        public void BeginTransaction()
        {
            if (transaction == null)
            {
                Console.WriteLine("Beggining transaction");
                transaction = context.Database.BeginTransaction();
            }
        }

        public void BeginTransaction(IsolationLevel isolationLevel)
        {
            if(transaction == null)
            {
                Console.WriteLine("Beggining transaction");
                transaction = context.Database.BeginTransaction(isolationLevel); 
                
            }

        }

        public void CommitTransaction()
        {
            if(transaction != null)
            {
                transaction.Commit();
                transaction.Dispose();
                transaction = null;
            }
        }

        public void Dispose()
        {
            Dispose(true);  //Deal with disposing yourself so you know no matter what happens (e.g. exception occurs) the context will be closed 
            GC.SuppressFinalize(this);  //prevent redundant garbage collection of already disposed objects
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                    transaction = null;
                }
                if (context != null)
                {
                    context.Dispose();
                    context = null;
                }
            }
            Console.WriteLine("Successfully disposed");
        }
    }
}
